import { useModel } from "umi";
import { Form, Input, Button, message, Space } from "antd";
import { useReactive } from "ahooks";

import { UpdateCategory } from "../../_graphql/resources/";

const EditIncomeExpenseCategory = ({ record, categories, reloadData }) => {
    const { graphqlFetchPlatform } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const [form] = Form.useForm();

    const state = useReactive({
        loading: false,
    });

    let onFinish = async (values) => {
        state.loading = true;
        let res = await graphqlFetchPlatform({
            query: UpdateCategory,
            variables: {
                ...values,
                iecUuid: record.iecUuid,
                iecUpti: new Date().getUTCTime(),
            },
        });
        if (res) {
            message.success("成功修改收支类别信息");
            reloadData();
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    const validator = async (rule, value) => {
        if (value && /^[\u4e00-\u9fa5a-zA-Z0-9]{1,50}$/.test(value)) {
            let index = categories.findIndex((item) => item.iecName === value && item.iecUuid !== record.iecUuid);
            return index === -1 ? Promise.resolve() : Promise.reject("已存在相同的类别名称，请重新输入");
        } else {
            return Promise.reject("只能输入中文、英文、数字，最多50个字符");
        }
    };

    return (
        <div>
            <Form form={form} layout="horizontal" onFinish={onFinish} labelCol={{ span: 5 }} wrapperCol={{ span: 17 }} initialValues={record}>
                <Form.Item label="类别类型" name="iecType">
                    <Input readOnly />
                </Form.Item>

                <Form.Item label="类别编码" name="iecIdno">
                    <Input readOnly />
                </Form.Item>

                <Form.Item label="类别名称" name="iecName" validateTrigger="onBlur" rules={[{ required: true, validator: validator }]}>
                    <Input readOnly={record.iecStat} />
                </Form.Item>

                <Form.Item label="类别说明" name="iecRemk">
                    <Input />
                </Form.Item>

                <div style={{ marginTop: 20, textAlign: "center" }}>
                    <Space>
                        <Button loading={state.loading} type="primary" htmlType="submit">
                            保存类别信息
                        </Button>
                        <Button loading={state.loading} onClick={onCloseGlobalModal}>
                            取消
                        </Button>
                    </Space>
                </div>
            </Form>
        </div>
    );
};

export default EditIncomeExpenseCategory;
